<script setup lang="ts">
import { reactive,watchEffect,ref } from 'vue'
import locale from "element-plus/lib/locale/lang/zh-cn"
import { useUserStore } from '@/store/user';
import { useMainStore } from '@/store/index'
import { useTabStore } from '@/store/tab';
import type { FormInstance, FormRules } from 'element-plus'
import { addPostgresInfo as addPostgresInfoApi } from '@/api/tab';

const userStore = useUserStore();
const store = useMainStore()
const tabStore = useTabStore();
const dialogFormVisible = ref<boolean>(false)
const ruleFormRef = ref<FormInstance>()
interface RuleForm {
  geom:string,
  contractorName:string,
  countyName:string,
  townName:string,
  villageName:string,
  farmName:string,
  phone:string,
  area:number,
  annualRent:number,
  circulationTime:string,
  mu:number,
  isFarm:string,
  townlist:string,
  villageNameId:string,
}
const form = reactive<RuleForm>({
  geom:'',
  contractorName:'',
  countyName: "",
  townName:'',
  villageName:'',
  farmName:'',
  phone:'',
  annualRent:0,
  circulationTime:'',
  area:0,
  mu:0,
  isFarm:'0',
  townlist:'',
  villageNameId:'',
})
const isOverBtnShow = ref<boolean>(false)

const rules = reactive<FormRules<RuleForm>>({
  townlist: [{
      required: true,
      message: '请选择行政区',
      trigger: 'change',
  }],
  contractorName: [{
      required: true,
      message: '请输入承包人',
      trigger: 'change',
  }]
})

const props1 = {
  value:'name',
  label:'name',
  children:'villageVoList'
}

const changeXZQ = (node) => {
  if(node.length==2) {
    tabStore.townArr.map(res => {
      if(res.name == node[0]) {
        res.villageVoList.map(ele => {
          ele.name == node[1]?form.villageNameId=ele.id:''
        })
      }
    })
    form.townName = node[0]
    form.villageName = node[1]
  }
}

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if(form.isFarm=='0'){
        form.farmName = form.farmName + '家庭农场'
      }
      await addPostgresInfoApi(form).then(res => {
        ElMessage({ message: res.msg, type: 'success' })
        dialogFormVisible.value = false
        window.sytdlzwma.reload()
      })
    }
  })
}

// 绘制面层
const drawlhmc = () => {
  isOverBtnShow.value = true
  window.sytdlzwma.unbindPopup()
  window.drawLayer.startDraw({
    type: "polygon",
    attr:{
      layer: "",
      surfaceArea:''
    },
    style:{
      fill:false,
      outline:true,
      outlineWidth:3,
      outlineColor:'#fff'
    },
    success:(graphic:any) => {
      form.area = (graphic.area*1).toFixed(2)
      form.mu = (form.area/666.67).toFixed(2)
      dialogFormVisible.value = true
      isOverBtnShow.value = false
      var geom = graphic.toGeoJSON({closure:true,noAlt:true}).geometry
      geom.type = 'MultiPolygon'
      geom.coordinates = [geom.coordinates]
      form.geom = JSON.stringify(geom)
    }
  })
}

const cancel = () =>{
  dialogFormVisible.value = false
  window.drawLayer.clear()
  ruleFormRef.value.resetFields()
}

/* 结束绘制 */
const overDrawConfirm = () => {
  isOverBtnShow.value = dialogFormVisible.value = false
  window.drawLayer.clearDrawing()
}

watchEffect(() => {
  if(store.activeBtn!=6&&store.activeBtn!='')[window.drawLayer.clear(),isOverBtnShow.value =false]
})
</script>

<template>
  <div class="TabbarBtn" v-if="userStore.roles.includes('superadmin')||userStore.roles.includes('farmAdmin')">
    <el-tooltip
      class="box-item"
      effect="dark"
      content="添加农场"
      placement="left"
    >
    <div class="iconBox" @click="[store.activeBtn=6,drawlhmc()]">
      <img src="@/assets/image/vector.png" alt="">
    </div>
    </el-tooltip>
  </div>

  <el-dialog v-model="dialogFormVisible" title="新增土地信息" width="500" :close-on-click-modal="false" @closed="cancel()">
    <el-form ref="ruleFormRef" :model="form" :rules="rules">
      <el-form-item label="行政区" prop="townlist">
        <el-cascader v-model="form.townlist" :options="tabStore.townArr" :props="props1" clearable placeholder="请选择行政区" @change="changeXZQ"></el-cascader>
      </el-form-item>
      <el-form-item label="是否是农场" prop="isFarm">
          <el-switch v-model="form.isFarm" active-value="0" inactive-value="1" />
        </el-form-item>
      <el-form-item label="农场名称" v-show="form.isFarm=='0'" prop="farmName">
        <el-input v-model="form.farmName" autocomplete="off">
          <template #append>家庭农场</template>
        </el-input>
      </el-form-item>
      <el-form-item label="承包人" prop="contractorName">
        <el-input v-model="form.contractorName" autocomplete="off" />
      </el-form-item>
      <el-form-item label="年租金" prop="annualRent">
        <el-input v-model="form.annualRent" autocomplete="off" />
      </el-form-item>
      <el-form-item label="流转时间" prop="circulationTime">
        <el-config-provider :locale="locale">
          <el-date-picker
            v-model="form.circulationTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择流转时间"
          />
        </el-config-provider>
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" autocomplete="off" />
      </el-form-item>
      <el-form-item label="面积/㎡" prop="area">
        <el-input type="number" v-model="form.area" autocomplete="off" @input="form.mu=(form.area/666.67).toFixed(2)" />
      </el-form-item>
      <el-form-item label="面积/亩" prop="mu">
        <el-input type="number" v-model="form.mu" autocomplete="off" @input="form.area=(form.mu*666.67).toFixed(2)" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancel()">取消</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      </div>
    </template>
  </el-dialog>

  <div v-show="isOverBtnShow" class="overDraw-webview" @click="overDrawConfirm">
    <div class="overDraw-webview_box">
      取消绘制
    </div>
  </div>
</template>
